<script src="{{langJs}}"></script>
<w:js>Weline_CKEditorEditorManager::build/ckeditor.js</w:js>
<script>
    const HTTP_SERVER_LAG = window.site.base_host
    const watchdog = new CKSource.EditorWatchdog();

    window.watchdog = watchdog;

    watchdog.setCreator((element, config) => {
        return CKSource.Editor
            .create(element, config)
            .then(editor => {
                return editor;
            });
    });

    watchdog.setDestructor(editor => {
        return editor.destroy();
    });

    watchdog.on('error', handleSampleError);

    let editors = document.querySelectorAll('.editor');
    for (let i = 0; i < editors.length; i++) {
        let config = {}
        if ('{{ck_lang}}' !== 'zh') {
            config = {
                language: '{{ck_lang}}',
            }
        }
        let customConfig = {
            autosave: {
                waitingTime: 1000,
                save( editor ) {
                    return saveData( editor );
                }
            },
        }
        config = {...customConfig,...config}
        watchdog.create(editors[i], config).catch(handleSampleError).then(editor => {
            // handleStatusChanges(editor);
            // handleSaveButton(editor);
            // handleBeforeunload(editor);
        })
    }
    // Save the data to a fake HTTP server (emulated here with a setTimeout()).
    function saveData( editor ) {
        return new Promise( resolve => {
            setTimeout( () => {
                resolve();
                editor.sourceElement.textContent = editor.getData()
                $(editor.sourceElement).trigger('input')
                console.log( 'Saved', $(editor.sourceElement) );
                console.log( 'Saved', editor );
            }, HTTP_SERVER_LAG );
        } );
    }

    function handleSampleError(error) {
        const issueUrl = 'https://github.com/ckeditor/ckeditor5/issues';

        const message = [
            'Oops, something went wrong!',
            `Please, report the following error on ${issueUrl} with the build id "ttrdyk7gecet-v0iisoxip8i4" and the error stack trace:`
        ].join('\n');

        console.error(message);
        console.error(error);
    }

    // Handle clicking the "Save" button by sending the data to a
    // fake HTTP server (emulated here with setTimeout()).
    function handleSaveButton(editor) {
        const saveButton = document.querySelector('#save');
        const pendingActions = editor.plugins.get('PendingActions');

        saveButton.addEventListener('click', evt => {
            const data = editor.getData();

            // Register the action of saving the data as a "pending action".
            // All asynchronous actions related to the editor are tracked like this,
            // so later on you only need to check `pendingActions.hasAny` to check
            // whether the editor is busy or not.
            const action = pendingActions.add('Saving changes');

            evt.preventDefault();

            // Save the data to a fake HTTP server.
            setTimeout(() => {
                pendingActions.remove(action);

                // Reset isDirty only if the data did not change in the meantime.
                if (data == editor.getData()) {
                    isDirty = false;
                }

                updateStatus(editor);
            }, HTTP_SERVER_LAG);
        });
    }

    // Listen to new changes (to enable the "Save" button) and to
    // pending actions (to show the spinner animation when the editor is busy).
    function handleStatusChanges(editor) {
        editor.plugins.get('PendingActions').on('change:hasAny', () => updateStatus(editor));
        console.log(editor.getData())
        editor.model.document.on('change:data', () => {
            isDirty = true;
            updateStatus(editor);
        });
    }

    // If the user tries to leave the page before the data is saved, ask
    // them whether they are sure they want to proceed.
    function handleBeforeunload(editor) {
        const pendingActions = editor.plugins.get('PendingActions');

        window.addEventListener('beforeunload', evt => {
            if (pendingActions.hasAny) {
                evt.preventDefault();
            }
        });
    }

    function updateStatus(editor) {
        const saveButton = document.querySelector('#save');

        // Disables the "Save" button when the data on the server is up to date.
        if (isDirty) {
            saveButton.classList.add('active');
        } else {
            saveButton.classList.remove('active');
        }

        // Shows the spinner animation.
        if (editor.plugins.get('PendingActions').hasAny) {
            saveButton.classList.add('saving');
        } else {
            saveButton.classList.remove('saving');
        }
    }
</script>